package com.bw.controller.order;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.controller.information.PiMaterialController;
import com.bw.entity.information.PiCustomer;
import com.bw.entity.information.PiProcess;
import com.bw.entity.order.PiOrder;
import com.bw.entity.order.PiOrderLog;
import com.bw.entity.user.TbUser;
import com.bw.req.OrderExp;
import com.bw.resp.ResponseResult;
import com.bw.service.information.IPiCustomerService;
import com.bw.service.order.IPiOrderLogService;
import com.bw.service.order.IPiOrderService;
import com.bw.service.user.ITbUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.excelutils.ExcelException;
import net.sf.excelutils.ExcelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lizhengqian
 * @since 2020-06-20
 */
@RestController
@RequestMapping("/order")
public class PiOrderController {
    @Autowired
    private IPiOrderService orderService;
    @Autowired
    private IPiOrderLogService orderLogService;
    @Autowired
    private IPiCustomerService customerService;
    @Autowired
    private IPiOrderService iPiOrderService;
    @Autowired
    private ITbUserService userService;


    private final Logger logger= LoggerFactory.getLogger(PiMaterialController.class);

    @PostMapping("list/{page}/{size}")
    public ResponseResult list(@PathVariable("page") int page, @PathVariable("size") int size,@RequestBody PiOrder piOrder) { //参数json字符串
        logger.info("订单列表查询");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PageHelper.startPage(page, size);//开启分页查询
            QueryWrapper queryWrapper = new QueryWrapper();
            if (null != piOrder.getCode()) {
                queryWrapper.like("code", "%" + piOrder.getCode() + "%");
            }
            if (null != piOrder.getCustomerName()) {
                queryWrapper.like("customerName", "%" + piOrder.getCustomerName() + "%");
            }
            if (null != piOrder.getState()) {
                queryWrapper.like("state", "%" + piOrder.getState() + "%");
            }
            queryWrapper.ne("isdelete",0);
            queryWrapper.orderByDesc("updateDate");
//            System.out.println("********************************");
//            System.out.println(piOrder.getTbId());
//            queryWrapper.eq("tbId",piOrder.getTbId());
            List<PiOrder> piOrders = orderService.list(queryWrapper);//列表查询
            PageInfo pageInfo = new PageInfo(piOrders);//pagehelper封装好的分页实体类，将数据放进去
            result.setResult(pageInfo);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("查询失败:" + e.toString());
        }
        logger.info("订单列表查询结束");
        return result;

    }
    /*订单提交*/
    @PostMapping("tjOrder/{id}")
    public ResponseResult tjOrder(@PathVariable("id") Long id,@RequestBody TbUser user) {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PiOrder piOrder= orderService.getById(id);
            piOrder.setState(1);
            piOrder.setUpdateDate(new Date());
            piOrder.setUpdateUser(user.getId());
            orderService.saveOrUpdate(piOrder);
            PiOrderLog orderLog=new PiOrderLog();
            orderLog.setOrderId(piOrder.getId());
            orderLog.setTbId(user.getId());
            orderLog.setUpdatetime(new Date());
            orderLog.setRemarks(user.getUserName()+"已提交");
            orderLog.setUserName(user.getUserName());
            orderLogService.saveOrUpdate(orderLog);
            result.setMessage("提交成功");
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("提交失败:" + e.toString());
        }
        return result;
    }
    /*已工艺转已报价*/
    @PostMapping("offerOrder/{id}")
    public ResponseResult offerOrder(@PathVariable("id") Long id,@RequestBody TbUser user) {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PiOrder piOrder= orderService.getById(id);
            piOrder.setState(3);
            piOrder.setUpdateDate(new Date());
            piOrder.setUpdateUser(user.getId());
            orderService.saveOrUpdate(piOrder);
            PiOrderLog orderLog=new PiOrderLog();
            orderLog.setOrderId(piOrder.getId());
            orderLog.setUpdatetime(new Date());
            orderLog.setTbId(user.getId());
            orderLog.setRemarks(user.getUserName()+"已报价");
            orderLog.setUserName(user.getUserName());
            orderLogService.saveOrUpdate(orderLog);
            result.setMessage("报价成功");
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("报价失败:" + e.toString());
        }
        return result;
    }
    /*转合同*/
    @PostMapping("trueOrder/{id}")
    public ResponseResult trueOrder(@PathVariable("id") Long id,@RequestBody TbUser user) {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PiOrder piOrder= orderService.getById(id);
            piOrder.setState(5);
            piOrder.setUpdateDate(new Date());
            piOrder.setUpdateUser(user.getId());
            orderService.saveOrUpdate(piOrder);
            PiOrderLog orderLog=new PiOrderLog();
            orderLog.setOrderId(piOrder.getId());
            orderLog.setUpdatetime(new Date());
            orderLog.setTbId(user.getId());
            orderLog.setRemarks(user.getUserName()+"已转合同");
            orderLog.setUserName(user.getUserName());
            orderLogService.saveOrUpdate(orderLog);
            result.setMessage("转合同成功");
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("转合同失败:" + e.toString());
        }
        return result;
    }

    /*关闭订单*/
    @PostMapping("closeOrder/{id}")
    public ResponseResult closeOrder(@PathVariable("id") Long id,@RequestBody TbUser user) {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PiOrder piOrder= orderService.getById(id);
            piOrder.setState(6);
            piOrder.setUpdateDate(new Date());
            piOrder.setUpdateUser(user.getId());
            orderService.saveOrUpdate(piOrder);
            PiOrderLog orderLog=new PiOrderLog();
            orderLog.setOrderId(piOrder.getId());
            orderLog.setUpdatetime(new Date());
            orderLog.setTbId(user.getId());
            orderLog.setRemarks(user.getUserName()+"已关闭");
            orderLog.setUserName(user.getUserName());
            orderLogService.saveOrUpdate(orderLog);
            result.setMessage("关闭成功");
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("关闭失败:" + e.toString());
        }
        return result;
    }
    /*已关闭的订单才可以进行删除*/
    @PostMapping("delOrder/{id}")
    public ResponseResult delOrder(@PathVariable("id") Long id,@RequestBody TbUser user) {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PiOrder piOrder=orderService.getById(id);
            piOrder.setIsDelete(0);
            orderService.saveOrUpdate(piOrder);
            piOrder.setUpdateDate(new Date());
            piOrder.setUpdateUser(user.getId());
            orderService.saveOrUpdate(piOrder);
            PiOrderLog orderLog=new PiOrderLog();
            orderLog.setOrderId(piOrder.getId());
            orderLog.setUpdatetime(new Date());
            orderLog.setTbId(user.getId());
            orderLog.setRemarks("删除订单");
            orderLog.setUserName(user.getUserName());
            orderLogService.saveOrUpdate(orderLog);
            result.setMessage("删除成功");
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("删除失败:" + e.toString());
        }
        return result;
    }
    @GetMapping("orderRecord/{id}")
    public ResponseResult orderRecord(@PathVariable("id") Long id) {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("orderId",id);
            List<PiOrderLog> piOrderLogs= orderLogService.list(queryWrapper);
            result.setResult(piOrderLogs);
            result.setMessage("订单记录成功");
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("订单记录失败:" + e.toString());
        }
        return result;
    }


    @GetMapping("/exportExcel/{id}")
    public void exportExcel(HttpServletResponse response,@PathVariable("id")Long id) throws IOException, ExcelException {
        OrderExp orderExp= orderService.find(id);

        response.setHeader("Content-Type","application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+new String("导出报价单".getBytes(),"iso-8859-1")+".xls");
        ClassPathResource classPathResource = new ClassPathResource("xls/quotation.xls");
        InputStream inputStream = classPathResource.getInputStream();//获取excel的模板
        ExcelUtils.addValue("customer",orderExp.getCustomer());
        ExcelUtils.addValue("user",orderExp.getUser());
        ExcelUtils.addValue("order",orderExp.getOrder());
        ExcelUtils.addValue("orderItemList",orderExp.getOrderItemList());




        ExcelUtils.export(inputStream,ExcelUtils.getContext(),response.getOutputStream());//第一个参数：模板的流。第三个：输出到哪

    }
    @PostMapping("/getOrderPrice")
    public ResponseResult getOrderPrice() {
        logger.info("查询订单订单金额开始");
        ResponseResult result=ResponseResult.SUCCESS();
        try{
            List<Map> list= orderService.getOrderPrice();
            List orderCode=new ArrayList();
            List orderPriceIt=new ArrayList();
            for(int i=0;i<list.size();i++){
                orderCode.add(list.get(i).get("code"));
                orderPriceIt.add(list.get(i).get("priceIt"));
            }
            Map<String,List> mapInfo=new HashMap<String,List>();
            mapInfo.put("code",orderCode);
            mapInfo.put("priceIt",orderPriceIt);
            result.setMessage("查询订单订单成功");
            result.setResult(mapInfo);
        }catch (Exception e){
            result.setMessage("查询订单订单金额错误"+e.toString());
            e.printStackTrace();
            result.setSuccess(false);
        }

        logger.info("查询订单订单金额结束");
        return result;
    }


    @PostMapping("/getxiaoshoue")
    public ResponseResult getxiaoshoue() {
        logger.info("查询销售销售额占比开始");
        ResponseResult result=ResponseResult.SUCCESS();
        try{
            List<Map> list= orderService.getxiaoshoue();
            List userName=new ArrayList<>();
            List userPrice=new ArrayList();
            for (int i=0;i<list.size();i++){
                userName.add(list.get(i).get("name"));
                userPrice.add(list.get(i));
            }
            Map mapInfo=new HashMap();
            mapInfo.put("userName",userName);
            mapInfo.put("userPrice",userPrice);
            result.setResult(mapInfo);
            result.setMessage("查询销售销售额占比成功");

        }catch (Exception e){
            result.setMessage("查询销售销售额占比错误"+e.toString());
            e.printStackTrace();
            result.setSuccess(false);
        }

        logger.info("查询销售销售额占比结束");
        return result;
    }


    @GetMapping("/findZhu")
    public ResponseResult findZhu(@PathVariable("id") Long id) {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            List<PiOrder> list = iPiOrderService.list();

        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("订单记录失败:" + e.toString());
        }
        return result;
    }
}
